//
//  59. 螺旋矩阵 II.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/8/22.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution59 {
    // 非常经典的写法
    func generateMatrix(_ n: Int) -> [[Int]] {
        var matrix = Array(repeating: Array(repeating: 0, count: n), count: n)
        let directions = [[0,1],// 右
                          [1,0], // 下
                          [0,-1], // 左
                          [-1,0]]// 上
        var curNum = 1
        var i = 0
        var j = 0
        var directionIndex = 0
        while curNum <= n * n {
            matrix[i][j] = curNum
            curNum += 1
            // 在当前的方向上，计算下一行，与下一列
            let nextRow = i + directions[directionIndex][0]
            let nextColumn = j + directions[directionIndex][1]
            // 查看是否需要换方向
            if nextRow < 0 ||
                nextRow >= n ||
                nextColumn < 0 ||
                nextColumn >= n ||
                matrix[nextRow][nextColumn] != 0
                {
                directionIndex = (directionIndex + 1) % 4;
            }
            // 计算修改过过后的真正行与列
            i = i + directions[directionIndex][0];
            j = j + directions[directionIndex][1]
        }
        return matrix
    }
    static func test() {
        let solution = Solution59()
        let n = 3
        let result = solution.generateMatrix(n)
        print(result)
    }
}
